package system

import (
	"errors"
	"os/exec"
	"strings"

	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data"
)

type RegisterUtil struct{}

// 取注册中的序列号
// key 干扰串
func (this RegisterUtil) GetRegisterSeries(key string) string {
	cpuid := this.GetCPUID()
	return data.Md5{}.Upper(cpuid, ";", key)
}

// 根据注册序列号创建注册码
// registerSeries 注册序列号
func (this RegisterUtil) CreateRegisterCode(registerSeries string) (string, error) {
	registerSeries = strings.ToUpper(strings.TrimSpace(registerSeries))
	if registerSeries == "" {
		return "", errors.New("序列号为空")
	}

	if len(registerSeries) < 30 {
		return "", errors.New("序列号长度不符,应为32位")
	}

	var build strings.Builder
	for i := 0; i < 6; i++ {
		str := string(registerSeries[i*5] + 1)
		if strings.Contains(":;<=>?@[\\]^_`{|}~", str) {
			str = "A"
		}

		build.WriteString(str)
	}

	return build.String(), nil
}

// 根据注册序列号判断注册码是否正确
// registerSeries 注册序列号
// key 注册码
func (this RegisterUtil) ValidCode(registerSeries, key string) (bool, error) {
	registerSeries = strings.ToUpper(strings.TrimSpace(registerSeries))
	if registerSeries == "" {
		return false, errors.New("序列号为空")
	}

	if len(registerSeries) < 30 {
		return false, errors.New("序列号长度不符,应为32位")
	}

	key = strings.ToUpper(strings.TrimSpace(key))

	if "" == key {
		return false, errors.New("注册码为空")
	}

	if len(key) != 6 {
		return false, errors.New("注册码长度不符,应为6位")
	}

	for i := 0; i < 6; i++ {
		ch := key[i]
		t := registerSeries[i*5] + 1

		str := string(t)
		if strings.Contains(":;<=>?@[\\]^_`{|}~", str) {
			t = 65 //'A'
		}

		if ch != t {
			return false, errors.New("注册码不符")
		}
	}

	return true, nil
}

// GetCPUID 获取cpuid
func (this RegisterUtil) GetCPUID() string {
	var cpuid string
	cmd := exec.Command("wmic", "cpu", "get", "processorid")
	b, e := cmd.CombinedOutput()

	if e != nil {
		return ""
	}

	cpuid = string(b)
	cpuid = cpuid[12 : len(cpuid)-2]
	cpuid = strings.ReplaceAll(cpuid, "\n", "")

	return cpuid
}
